<?php

class Member2024Action extends CommonAction{

    /**
     * 精选商标
     * @return void
     */
    public function best(){
        if ( !$this->checkLogin(true) ) {
            header('Location:/member2024/login.html');
            exit();
        }
        $sn = $this->_get('sn', 'trim', '');
        $cid = $this->_get('cid', 'trim', '');
        $name = $this->_get('name', 'trim', '');
        $trademarkStatus = $this->_get('trademarkStatus', 'trim', '');
        $topStatus = $this->_get('topStatus', 'trim', '');
        //构造搜索条件
        $where = array();
        $where['is_deleted'] = 0;
        $params = '';
        if ($sn != '') {
            $params .= '/sn/' . $sn;
            $where['sn'] = $sn;
        }
        if ($cid != '' && $cid > 0) {
            $params .= '/cid/' . $cid;
            $where['cate'] = $cid;
        }
        if ($name != '') {
            $params .= '/name/' . $name;
            $where['name'] = $name;
        }
        if ($trademarkStatus != '') {
            $params .= '/trademarkStatus/' . $trademarkStatus;
            if( intval($trademarkStatus) == 0 ){
                $where['status'] = 0;
            }
            if( intval($trademarkStatus) == 1 ){
                $where['status'] = 1;
            }
            if( intval($trademarkStatus) == 2 ){
                $where['status'] = 2;
            }
        }
        if ($topStatus != '') {
            $params .= '/topStatus/' . $topStatus;
            if( intval($topStatus) == 0 ){
                $where['top'] = 0;
            }
            if( intval($topStatus) == 1 ){
                $where['top'] = 1;
            }
        }

        $this->M->page['no'] = $this->_get('p') ? $this->_get('p', 'intval') : 1;
        $this->M->page['num'] = 10;
        $this->M->page['total'] = ceil(M("trademarks_best")->where($where)->count() / $this->M->page['num']);
        $list = M("trademarks_best")
            ->where($where)
            ->order('top desc, top_time desc, sort desc, updated_at desc, id desc')
            ->limit($this->page_limit())
            ->select();
        foreach ($list as $k => $v) {
            $list[$k]['catename'] = $this->getCategory($v['cate']);
            $list[$k]['origin_price'] = $v['price'];
            //计算最新价格
            $newprice = intval($v['price'] * (100 + $this->buyFasterRate) / 100);
            if( $newprice < ($v['price'] + $this->buyFasterLow) ){
                $list[$k]['price'] = $v['price'] + $this->buyFasterLow;
            }else if( $newprice > ($v['price'] + $this->buyFasterHigh) ){
                $list[$k]['price'] = $v['price'] + $this->buyFasterHigh;
            }else{
                $list[$k]['price'] = $newprice;
            }
        }
        $pageurl = '/member2024/best' . $params . '/p/*.html';
        $this->set_pages($pageurl);
        $this->assign('sn', $sn);
        $this->assign('name', $name);
        $this->assign('cid', $cid);
        $this->assign('topStatus', $topStatus);
        $this->assign('trademarkStatus', $trademarkStatus);
        $this->assign('category',$this->getCategory());
        $this->assign('trademarklist', $list);
        $this->display();
    }

    /**
     * 商标仓库
     * @return void
     */
    public function origintrademarks(){
        if ( !$this->checkLogin(true) ) {
            header('Location:/member2024/login.html');
            exit();
        }
        //查询已设置精选的商标
        $relateids = array();
        $bestList= M("trademarks_best")->field("relateid")->where("is_deleted = 0")->select();
        foreach ($bestList as $k => $v){
            array_push($relateids,$v['relateid']);
        }
        $params = '';
        //当前页码
        $page = $this->_get('p') ? $this->_get('p', 'intval') : 1;
        $pageSize = 50;
        //分类
        $cid = $this->_get("cid","intval");
        //开始价格
        $ps = $this->_get("ps","intval");
        //结束价格
        $pe = $this->_get("pe","intval");
        //价格由低到高,排序规则，1.价格由低到高 2.价格由高到低 3.新上传的在前面 4.新上传的在后面 5.星星由高到低 0.默认排序
        $orderBy = 1;
        //接口请求地址
        $apiUrl = 'https://biaobiaoku.com/api/search?';
        $param = array();
        $param["ip"] = empty($_SERVER["REMOTE_ADDR"]) ? "47.102.187.210" : $_SERVER["REMOTE_ADDR"];
        $param["current"] = empty($page) ? 1 : $page;
        $param["limit"] = $pageSize;
        $param["textType"] = '智能';
        $param["sqNum"] = "1-80";//注册人申请量 1-90
        //搜索模式 可选项有: 0至少包含一个字 1.开头包含 3.包含全部 4.精准匹配 默认是3
        $param["searchMode"] = 3;
        //搜索类型，可选项有:0智能,1商标名,2注册号,3申请人
        $st = $this->_get("textType",'intval');
        if( $st == 0 || $st == "智能" ){
            $param["textType"] = '智能';
            $params .= '/textType/' . $st;
        }elseif( $st == 1 || $st == "商标名" ){
            $param["textType"] = '商标名';
            $params .= '/textType/' . $st;
        }elseif( $st == 2 || $st == "注册号" ){
            $param["textType"] = '注册号';
            $params .= '/textType/' . $st;
        }elseif( $st == 3 || $st == "申请人" ){
            $param["textType"] = '申请人';
            $params .= '/textType/' . $st;
        }else{
            $param["textType"] = '智能';
            $params .= '/textType/' . $st;
        }
        //搜索内容
        $text = $this->_get("text",'trim');
        if( !empty($text) ){
            $param["text"] = $text;
            $params .= '/text/' . $text;
        }
        if( !empty( $cid ) ){
            $param["leis"] = $cid;
            $params .= '/cid/' . $cid;
        }
        $param["orderCode"] = $orderBy;
        if ($ps > 0) {
            $param["priceStart"] = $ps;
            $params .= '/ps/' . $ps;
        }
        if ($pe > 0) {
            $param["priceEnd"] = $pe;
            $params .= '/pe/' . $pe;
        }
        $apiUrl = $apiUrl . http_build_query($param);
        $res = file_get_contents($apiUrl);
        $response = json_decode($res, true, JSON_UNESCAPED_UNICODE);
        if ( $response['code'] == 0) {
            $total = $response['data']['total'];
            $list = $response['data']['results'];
            if ( !empty($list) ) {
                $vos = array();
                foreach ($list as $k => $v) {
                    $vos[$k]['id'] = $v['id'];
                    //判断是否设置精选
                    $vos[$k]['best'] = 0;
                    if( in_array($v['id'], $relateids) ){
                        $vos[$k]['best'] = 1;
                    }
                    $vos[$k]['lei'] = $v['lei'];
                    $vos[$k]['lei_name'] = $this->getCategory($v['lei']);
                    $vos[$k]['name'] = $v['name'];
                    $vos[$k]['brandId'] = $v['brandId'];
                    $vos[$k]['goods_service'] = $v['goods'];
                    $vos[$k]['goods_sn'] = $v['team'];
                    $vos[$k]['brother_cate'] = ( !empty( $v['brother'] ) && strtolower($v['brother']) != 'null' ) ? $v['brother'] : "";
                    $vos[$k]['goods_service_num'] = $v['xxNum'];
                    $vos[$k]['thumb_image'] = "https://color.picer.cdn.biaobiaoku.com/" . $v['brandId'] . "-" . $v['picHash'] . "-250.png";
                    $vos[$k]['trademark_image'] = "https://brand.picer.cdn.biaobiaoku.com/" . $v['brandId'] . "-" . $v['picHash'] . ".jpg";
                    $vos[$k]['origin_price'] = $v['price'];
                    //计算最新价格
                    $newprice = intval($v['price'] * (100 + $this->buyFasterRate) / 100);
                    if( $newprice < ($v['price'] + $this->buyFasterLow) ){
                        $vos[$k]['price'] = $v['price'] + $this->buyFasterLow;
                    }else if( $newprice > ($v['price'] + $this->buyFasterHigh) ){
                        $vos[$k]['price'] = $v['price'] + $this->buyFasterHigh;
                    }else{
                        $vos[$k]['price'] = $newprice;
                    }
                }
            }
            $totalPage = 0;
            if( $total >0 ){
                $totalPage = ceil( $total / $param["limit"] );
            }
            $this->M->page['no'] = $page;
            $this->M->page['num'] = $pageSize;
            $this->M->page['total'] = $totalPage;
            $this->assign('trademarklist',$vos);
        }
        $pageurl = '/member2024/origintrademarks' . $params . '/p/*.html';
        $this->set_pages($pageurl);
        $this->assign('text', $text);
        $this->assign('textType', $st);
        $this->assign('ps', $ps);
        $this->assign('pe', $pe);
        $this->assign('cid', $cid);
        $this->assign('category',$this->getCategory());
        $this->display();
    }

    /**
     * 设置精选
     * @return void
     */
    public function setOriginTrademarksBest(){
        if ($this->checklogin(true) == false) {
            $this->ajaxError('您长时间未操作，已退出登录，请重新登录！');
        }
        $id = $this->_post('id','trim');
        $where = array();
        $where['relateid'] = $id;
        $where['is_deleted'] = 0;
        $trademark = M("trademarks_best")->where($where)->find();
        if( !empty($trademark) ){
            return $this->ajaxError('已是精选，不可重复设置！');
        }
        $ip = empty($_SERVER["REMOTE_ADDR"]) ? "47.102.187.210" : $_SERVER["REMOTE_ADDR"];
        $url = 'https://biaobiaoku.com/api/get-info-by-id?id='.$id."&ip=".$ip;
        $res = file_get_contents($url);
        $response = json_decode($res,true,JSON_UNESCAPED_UNICODE);
        $code = $response['code'];
        if( $code != 0 ){
            return $this->ajaxError($response['msg']);
        }
        $trademark = $response['data'];
        if( empty( $trademark ) ){
            return $this->ajaxError("获取商标仓库商标信息失败！反馈内容为空！");
        }
        $data = array();
        $data['name'] = $trademark['name'];
        $data['sn'] = $trademark['brandId'];
        $data['relateid'] = $trademark['id'];
        $data['cate'] = intval($trademark['lei']);
        $data['price'] = $trademark['price'];
        $data['group_sn'] = $trademark['team'];
        $data['goods_name'] = $trademark['goods'];
        //处理商标图片
        $data['thumb_image'] = "https://color.picer.cdn.biaobiaoku.com/".$trademark['brandId']."-".$trademark['picHash']."-250.png";
        $data['origin_image'] = "https://brand.picer.cdn.biaobiaoku.com/".$trademark['brandId']."-".$trademark['picHash'].".jpg";
        $data['registered_time'] = $trademark['registeredDate'];
        $data['top'] = 0;
        $data['sort'] = 0;
        $data['handle_status'] = 1;
        $data['status'] = 1;
        $data['is_deleted'] = 0;
        $data['create_at'] = date("Y-m-d H:i:s");
        $data['update_at'] = date("Y-m-d H:i:s");
        $F = M("trademarks_best")->add($data);
        if( !$F ){
            $this->ajaxError('设置精选失败！');
        }
        $this->ajaxSuccess('设置精选成功！');
    }

    /**
     * 刷新信息
     * @return void
     */
    public function refreshOriginTrademarksBest(){
        $id = $this->_get('id','trim');
        $where = array();
        $where['relateid'] = $id;
        $where['is_deleted'] = 0;
        $trademark = M("trademarks_best")->where($where)->find();
        if( empty($trademark) ){
            return $this->ajaxError("trademark is not exits");
        }
        $ip = empty($_SERVER["REMOTE_ADDR"]) ? "47.102.187.210" : $_SERVER["REMOTE_ADDR"];
        $url = 'https://biaobiaoku.com/api/get-info-by-id?id='.$id."&ip=".$ip;
        $res = file_get_contents($url);
        $response = json_decode($res,true,JSON_UNESCAPED_UNICODE);
        $code = $response['code'];
        if( $code != 0 ){
            return $this->ajaxError('api error');
        }
        $trademark = $response['data'];
        if( empty( $trademark ) ){
            $data = array();
            $data['is_deleted'] = 1;
            $data['remark'] = "获取商标仓库商标信息失败！反馈内容为空！";
            $data['update_at'] = date("Y-m-d H:i:s");
            $data['deleted_at'] = date("Y-m-d H:i:s");
            M("trademarks_best")->where($where)->save($data);
            return $this->ajaxError("trademark info is null");
        }
        $data = array();
        $data['name'] = $trademark['name'];
        $data['sn'] = $trademark['brandId'];
        $data['cate'] = intval($trademark['lei']);
        $data['price'] = $trademark['price'];
        $data['group_sn'] = $trademark['team'];
        $data['goods_name'] = $trademark['goods'];
        //处理商标图片
        $data['thumb_image'] = "https://color.picer.cdn.biaobiaoku.com/".$trademark['brandId']."-".$trademark['picHash']."-250.png";
        $data['origin_image'] = "https://brand.picer.cdn.biaobiaoku.com/".$trademark['brandId']."-".$trademark['picHash'].".jpg";
        $data['registered_time'] = $trademark['registeredDate'];
        $data['update_at'] = date("Y-m-d H:i:s");
        $F = M("trademarks_best")->where($where)->save($data);
        if( !$F ){
            $this->ajaxError('error');
        }
        $this->ajaxSuccess('success');
    }

    /**
     * 删除精选
     * @return void
     */
    public function delBest(){
        if ($this->checklogin(true) == false) {
            $this->ajaxError('您长时间未操作，已退出登录，请重新登录！');
        }
        $id = $this->_post('id','trim');
        $where = array();
        $where['id'] = $id;
        $where['is_deleted'] = 0;
        $trademark = M("trademarks_best")->where($where)->find();
        if( empty($trademark) ){
            return $this->ajaxError('精选商标不存在！');
        }
        $data = array();
        $data['is_deleted'] = 1;
        $data['update_at'] = date("Y-m-d H:i:s");
        $data['deleted_at'] = date("Y-m-d H:i:s");
        $F = M("trademarks_best")->where($where)->save($data);
        if( !$F ){
            $this->ajaxError('删除精选失败！');
        }
        $this->ajaxSuccess('删除精选成功！');
    }

    /**
     * 设置置顶
     * @return void
     */
    public function setTop(){
        if ($this->checklogin(true) == false) {
            $this->ajaxError('您长时间未操作，已退出登录，请重新登录！');
        }
        $id = $this->_post('id','trim');
        $where = array();
        $where['id'] = $id;
        $where['is_deleted'] = 0;
        $trademark = M("trademarks_best")->where($where)->find();
        if( empty($trademark) ){
            return $this->ajaxError('精选商标不存在！');
        }
        $data = array();
        $data['top'] = 1;
        $data['top_time'] = date("Y-m-d H:i:s");
        $data['update_at'] = date("Y-m-d H:i:s");
        $F = M("trademarks_best")->where($where)->save($data);
        if( !$F ){
            $this->ajaxError('置顶失败！');
        }
        $this->ajaxSuccess('置顶成功！');
    }

    /**
     * 取消置顶
     * @return void
     */
    public function cancelTop(){
        if ($this->checklogin(true) == false) {
            $this->ajaxError('您长时间未操作，已退出登录，请重新登录！');
        }
        $id = $this->_post('id','trim');
        $where = array();
        $where['id'] = $id;
        $where['is_deleted'] = 0;
        $trademark = M("trademarks_best")->where($where)->find();
        if( empty($trademark) ){
            return $this->ajaxError('精选商标不存在！');
        }
        $data = array();
        $data['top'] = 0;
        $data['top_time'] = NULL;
        $data['update_at'] = date("Y-m-d H:i:s");
        $F = M("trademarks_best")->where($where)->save($data);
        if( !$F ){
            $this->ajaxError('取消置顶失败！');
        }
        $this->ajaxSuccess('取消置顶成功！');
    }

    /**
     * 登录页面
     */
    public function login(){
        if ($this->checkLogin(true)) {
            header('Location:/');
        }
        $re = $this->_get('re', 'trim', '');
        if ($re) {
            session('loginto', base64_decode($re));
        } else {
            if (!session('loginto')) {
                session('loginto', '/member2024/best.html');
            }
        }
        $this->display('login');
    }

    /**
     * 登录提交AJAX
     */
    public function dologin(){
        $post = $this->boxpost();
        $logerr = S('loginerr' . $post['username']) ? S('loginerr' . $post['username']) : 0;
        if ($logerr >= 5) {
            unset($_SESSION['verify']);
            $this->ajaxError('您的错误次数过多，请一小时后再试');
        }
        $post['verifycode'] = trim($post['verifycode']);
        if(empty($post['verifycode'])){
            unset($_SESSION['verify']);
            $this->ajaxError('请输入图片验证码');
        }
        if (!$this->verifycheck($post['verifycode'])) {
            unset($_SESSION['verify']);
            $this->ajaxError('图片验证码输入错误');
        }
        //查询用户基础信息
        $member = M("admin_user")->where(array('user_name' => $post['username'], 'is_deleted' => 0))->find();
        if (!$member) {
            $member = M("admin_user")->where(array('user_mobile' =>$post['username'], 'is_deleted' => 0))->select();
            if (!$member) {
                unset($_SESSION['verify']);
                $this->ajaxError("用户不存在");
            }
            if (count($member) > 1) {
                unset($_SESSION['verify']);
                $this->ajaxError('您的帐号只能通过用户名登录');
            }
            $member = $member[0];
        }
        //获取加密密码
        $submitpasswd = $this->gen_password($post['password']);
        if ( $submitpasswd != $member['user_pwd'] ) {
            S('loginerr' . $post['username'], $logerr + 1, 3600);
            unset($_SESSION['verify']);
            $this->ajaxError("密码错误");
        }
        if( $member['disabled_status'] == 1){
            $this->ajaxError("账户已被禁用，暂时无法登录");
        }
        if( $member['status'] == 0){
            $this->ajaxError("账户未启用，暂时无法登录");
        }
        //如果是代理，则查询代理信息
        if( $member['role_id'] >= 3 ){
            $this->ajaxError("非管理员账户，暂时无法登录");
        }
        $session_id = session_id();
        S('pc_session_login_sessionId'.$member['id'],$session_id,86400);
        session('member', $member);
        session('loginto', '');
        $this->ajaxSuccess("登录成功");
    }

    /**
     * 退出
     */
    public function logout(){
        session('member',null);
        header('Location:/member2024/login.html');
    }

}